package com.frontend.authservice.service.Impl.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.frontend.authservice.Entity.SysUser;
import com.frontend.authservice.mapper.SysUserMapper;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Resource
    private SysUserMapper sysUserMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 构建查询条件
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", username)        // 注意字段名
                .eq("del_flag", "0")                // 未删除
                .eq("status", "0");                 // 状态正常
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);



        // 2. 检查用户是否存在
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        // 4. 构建完整的 UserDetails 对象（包含密码）
        return User.builder()
                .username(sysUser.getUserName())
                //密码验证是由 Spring Security 自动完成的：
                //你只需要在 loadUserByUsername 中返回包含正确加密密码的 UserDetails
                //Spring Security 会自动比较用户输入的密码和数据库中的密码
                //你不需要手动验证密码
                .password(sysUser.getPassword())      // 关键：数据库中的加密密码
                .authorities("USER")                  // 实际项目中应该查询真实权限
                .accountExpired(false)
                .accountLocked("1".equals(sysUser.getStatus()))
                .credentialsExpired(false)
                .disabled("1".equals(sysUser.getStatus()) || "2".equals(sysUser.getDelFlag()))
                .build();


    }
}
